package com.user.query.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * Created by ricky on 2017/3/15.
 *  自定义线程异常捕获
 * @author 华源润通郑州开发部
 * @version 1.0
 */
public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("捕获的异常："+t.getName()+"--"+e);
    }

    public static void main(String[] args) {
        //第一种通过工厂方式的
        ExecutorService e1= Executors.newCachedThreadPool(new HandlerThreadFactory());
        e1.execute(new myThread());
        //通过设置默认线程异常处理机制
        Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
        ExecutorService e2= Executors.newCachedThreadPool();
        e2.execute(new myThread());

    }
}

/**
 * 通过线程工厂设置默认异常捕获处理机制
 */
class HandlerThreadFactory implements ThreadFactory {

    @Override
    public Thread newThread(Runnable r) {
        Thread t=new Thread(r);
        t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
        return t;
    }
}

class myThread implements Runnable {
    @Override
    public void run() {
        throw new RuntimeException();
    }
}
